/*
 *  Copyright (c) 2022 李伟国
 *  online-judge is licensed under Mulan PSL v2.
 *  You can use this software according to the terms and conditions of the Mulan PSL v2.
 *  You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 *  THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 *  See the Mulan PSL v2 for more details.
 */

package edu.platform.service.impl;

import edu.platform.config.ConfigUploadProperties;
import edu.platform.service.IFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Service
public class FileServiceImpl implements IFileService {
    @Autowired
    ConfigUploadProperties configUploadProperties;


    @Override
    public String addFile(MultipartFile file) {
        if(file == null){
            return null;
        }
        File dir = new File(configUploadProperties.getImagePath());
        if(!dir.exists()){
            boolean mkdirs = dir.mkdirs();
        }
        String filename  = UUID.randomUUID()+file.getOriginalFilename();
        filename = filename.replaceAll("\\s+","").replaceAll("-","");
        File dest = new File(configUploadProperties.getImagePath()+File.separator+filename);
        try{
            file.transferTo(dest);
        }catch (IOException e){
            e.getStackTrace();
        }
        return configUploadProperties.getDomain()+"/file/image/"+filename;
    }

    @Override
    public String findFilePath(String filename) {
        File file = new File(configUploadProperties.getImagePath()+File.separator+filename);
        if(!file.exists()){
            return null;
        }
        return file.getPath();
    }

}
